package com.tian.pushlib

import com.tian.pushlib.extension.PushConfig
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPom
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.publish.maven.plugins.MavenPublishPlugin
import org.gradle.api.tasks.bundling.Jar
import org.gradle.kotlin.dsl.task
import java.net.URI


/**
 * 上传依赖库插件
 *
 * 会在当前项目中引入 maven-publish插件，关于maven-push插件的使用，移步下面
 *
 * @see <a href="https://docs.gradle.org/6.0/userguide/publishing_maven.html#publishing_maven:complete_example">maven publish</a>
 *
 *
 */
class PushLibPlugin : Plugin<Project> {

    private var pushConfig: PushConfig? = null

    override fun apply(target: Project) {
        pushConfig = target.extensions.create("pushConfig", PushConfig::class.java)

        // 给当前module引入 Mavenpush插件,在构建脚本中类似下面
        // lib-resource -> build.gradle
        // apply plugin 'maven-push'
        target.plugins.apply(MavenPublishPlugin::class.java)
        val publishingExtension = target.extensions.getByType(PublishingExtension::class.java)
        target.afterEvaluate {
            publishingExtension.publications {
                create("Tian", MavenPublication::class.java) {
                    groupId = pushConfig?.groupId
                    artifactId = pushConfig?.artifactId
                    version = pushConfig?.version
                    // 从debug构建
                    from(target.components.findByName("debug"))
                    artifact(androidSourceJar(target))

                    pom {
                        configPom(this, pushConfig!!)
                    }

                }
            }
            publishingExtension.repositories {
                maven {
                    url = URI(pushConfig?.repoUrl.orEmpty())
                    isAllowInsecureProtocol = true
                    credentials.apply {
                        username = pushConfig?.repoAccount.orEmpty()
                        password = pushConfig?.repoPwd.orEmpty()
                    }
                }
            }
        }
    }

    private fun configPom(pom: MavenPom, config: PushConfig) {
        pom.name.set(config.pomName)
        pom.description.set(config.pomDescription)

        // 打开方式设置为aar
        pom.packaging = "aar"

        // 开发者信息
        pom.developers {
            developer {
                id.set("Tian Technology")
                name.set("Tian android")
            }
        }
    }

    private fun androidSourceJar(target: Project): Task {
        return target.task("androidSourceJar", org.gradle.jvm.tasks.Jar::class) {
            archiveClassifier.set("sources")
            val libraryExt = target.extensions.getByName("android") as com.android.build.gradle.LibraryExtension
            from(libraryExt.sourceSets.findByName("main")!!.java.srcDirs)
        }
    }

}